package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sczmgk.hotline_pzh.DesJson.Des3;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.BaseActivity;
import com.sczmgk.hotline_pzh.callback.HttpFailCallback;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.callback.VerfyCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.db.impl.UserDaoImpl;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.dialog.MessageDialog;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.IndicatorInfos;
import com.sczmgk.hotline_pzh.entity.User;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.jpush.ExampleUtil;
import com.sczmgk.hotline_pzh.jpush.MainHomeDataObserver;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.BitmapUtils;
import com.sczmgk.hotline_pzh.utils.CommonUtils;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.MyToast;
import com.sczmgk.hotline_pzh.utils.SecurityCodeUtils;
import com.sczmgk.hotline_pzh.utils.TimerUtils;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.utils.UIUtils;
import com.sczmgk.hotline_pzh.view.CustomDeleteInfoView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.sczmgk.hotline_pzh.R.drawable.phone;

/**
 * Created by Administrator on 2016/12/1 0001.
 */
public class LoginActivity extends BaseActivity {

    private final String TAG = LoginActivity.class.getSimpleName();
    private static final int MSG_SET_ALIAS = 1001;

    private static final int MSG_SET_TAGS = 1002;
    /**标记从哪个页面进来*/
    private int fromtype;
    private final int JPUSH = 1;
    /*logo*/
    private ImageView mIvLogo;

    /*登录类型的控件以及账号登录与密码登录的类型选择*/
    private RadioGroup mRgLoginStyle;
    private RadioButton mRbPhone;
    private RadioButton mRbAccount;

    /*账号密码的图片*/
    private ImageView mIvAccount;
    private ImageView mIvPassword;

    /*获取验证码的按钮*/
    private Button mBtnGetSecurityCode;

    /*是否选择显示密码的控件*/
    private CheckBox mCbShowPassword;

    /*登录的按钮*/
    private Button mBtnLoginIn;

    /*随便看看与注册的按钮*/
    private Button mBtnLoginLook;
    private Button mBtnLoginRegist;

    /*历史记录的弹出框*/
    private PopupWindow popupWindow;

    /*账号和密码的输入控件*/
    private CustomDeleteInfoView mAccount;
    private CustomDeleteInfoView mPassword;

    /*用户信息的存储集合*/
    private List<User> userInfos = new ArrayList<>();

    /*选择的类型*/
    private static final String ACCOUNT_TYPE = "account_type";
    private static final String PHONE_TYPE = "phone_type";
    private String type = ACCOUNT_TYPE;

    //弹出框的ListView的Adapter
    private MyAdapter adapter;

    /*显示历史记录弹出框的按钮*/
    private ImageView mIvShowRecord;

    private LinearLayout mAccountLayout;

    /**找回密码*/
    private Button findPwd;
    /*账号右侧箭头和弹出框是否显示*/
    private AtomicBoolean isArrowDown = new AtomicBoolean();
    private AtomicBoolean popIsShowing = new AtomicBoolean();
    private ScrollView mSvLayout;

    private TimerUtils timerUtils;
    private MessageDialog errorDialog;

    @Override
    public void handleMessage(Message msg) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //将当前activity添加到集合中
        CommonUtils.addActivity(this);

        testJpush();
        init();
    }

    private void testJpush() {
        setRightBtnVisibility(View.VISIBLE);
        setRightBtnText(R.string.test_jpush);
        setRightBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setAlias(MyApp.imei+"_"+"0");
            }
        });
    }

    private void init() {

        setHeader();

        initView();

        setListener();

        initData();

    }

    /**
     * 设置头
     */
    private void setHeader() {
        setTitle(R.string.login_in);
        setLeftBtnVisibility(View.VISIBLE);
    }

    /**
     * 初始化控件
     */
    private void initView() {

        //当前activity控件
        mSvLayout = (ScrollView) findViewById(R.id.sv_login);

        //logo
        mIvLogo = (ImageView) findViewById(R.id.iv_login_logo);
        //类型选择
        mRgLoginStyle = (RadioGroup) findViewById(R.id.rg_login_style);
        mRbAccount = (RadioButton) findViewById(R.id.rb_login_account_number_select);
        mRbPhone = (RadioButton) findViewById(R.id.rb_login_phone_number_select);

        //输入账号和密码
        mAccount = (CustomDeleteInfoView) findViewById(R.id.cdi_login_account);
        mPassword = (CustomDeleteInfoView) findViewById(R.id.cdi_login_pwd);

        //账号和密码的图片
        mIvAccount = (ImageView) findViewById(R.id.iv_login_account);
        mIvPassword = (ImageView) findViewById(R.id.iv_login_pwd);

        //手机登录
        mBtnGetSecurityCode = (Button) findViewById(R.id.btn_login_get_security_code);

        //是否显示密码
        mCbShowPassword = (CheckBox) findViewById(R.id.cb_login_show_password);

        //显示箭头
        mIvShowRecord = (ImageView) findViewById(R.id.iv_login_show_record);

        //登录,随便看看,注册的按钮
        mBtnLoginIn = (Button) findViewById(R.id.btn_login_in);
        mBtnLoginLook = (Button) findViewById(R.id.btn_login_look);
        mBtnLoginRegist = (Button) findViewById(R.id.btn_login_regist);

        mAccountLayout = (LinearLayout) findViewById(R.id.ll_accout_layout);

        //默认选择账号登录
        RadioButton radioButton = (RadioButton) mRgLoginStyle.getChildAt(0);
        radioButton.setChecked(true);

        isArrowDown.set(false);
        popIsShowing.set(false);

        //设置输入类型
        mAccount.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
        mPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        findPwd = (Button)findViewById(R.id.btn_find_pwd);
    }

    /**
     * 设置监听
     */
    private void setListener() {

        //选择登录类型
        mRgLoginStyle.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_login_account_number_select:

                        //设置文本大小
//                        getResources().getDimension(R.dimen.indicator_text_size)
//                        getResources().getDimension(R.dimen.login_top_type_text_size)
                        mRbAccount.setTextSize(TypedValue.COMPLEX_UNIT_SP ,13);
                        mRbPhone.setTextSize(TypedValue.COMPLEX_UNIT_SP ,14);

                        //选择使用账号登录
                        type = ACCOUNT_TYPE;
                        setLoginType(View.GONE, View.VISIBLE, View.VISIBLE, R.drawable.account_number, R.drawable.password, false, R.string.login_et_account_password_hint);
                        mAccount.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
                        mPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

                        break;
                    case R.id.rb_login_phone_number_select:

                        //设置文本大小
                        mRbAccount.setTextSize(TypedValue.COMPLEX_UNIT_SP ,14);
                        mRbPhone.setTextSize(TypedValue.COMPLEX_UNIT_SP ,13);

                        if (timerUtils != null && timerUtils.timerIsRunning()){
                            timerUtils.stopTimer(mBtnGetSecurityCode);
                        }

                        //选择使用手机登录
                        type = PHONE_TYPE;
                        setLoginType(View.VISIBLE, View.INVISIBLE, View.GONE, phone, R.drawable.key, true, R.string.login_et_phone_password_hint);
                        mAccount.setInputType(InputType.TYPE_CLASS_PHONE);
                        mPassword.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);

                        break;
                }
            }
        });

        //显示密码
        mCbShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    //显示密码
                    mPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    //隐藏密码
                    mPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }

                //光标定在最后一位
                String password = mPassword.getText();
                if (!TextUtils.isEmpty(password)) {
                    mPassword.setSelection(password.length());
                }
            }
        });

//        //当文本发生改变时
//        mAccount.setMyOnTextchanged(new CustomDeleteInfoView.MyOnTextchanged() {
//            @Override
//            public void onTextChanged() {
//
//                //弹出pupupWindow
//                showPupWindow();
//
//                //当文本发生改变时,查找数据库
//                String inputInfo = mAccount.getText();
//                if (!Tools.isEmpty(inputInfo)) {
//                    if (userInfos != null) {
//                        List<User> filter = filterUserInfo(inputInfo);
//                        if (filter.size() > 0) {
//                            adapter.setUserInfos(filter);
//                            adapter.notifyDataSetChanged();
//                        } else {
//                            popupWindow.dismiss();
//                        }
//                    }
//                } else {
//                    adapter.setUserInfos(userInfos);
//                    adapter.notifyDataSetChanged();
//                }
//            }
//        });

        //获取验证码
        mBtnGetSecurityCode.setOnClickListener(new MyOnClickListener());
        //登录
        mBtnLoginIn.setOnClickListener(new MyOnClickListener());
        //随便看看
        mBtnLoginLook.setOnClickListener(new MyOnClickListener());
        //注册
        mBtnLoginRegist.setOnClickListener(new MyOnClickListener());
        //显示历史记录的按钮
        mIvShowRecord.setOnClickListener(new MyOnClickListener());
        //整体控件的点击
        mSvLayout.setOnClickListener(new MyOnClickListener());

        findPwd.setOnClickListener(new MyOnClickListener());

    }

    /**
     * 当文本发生改变的时候查找是否包含输入的内容并显示
     *
     * @param inputInfo
     * @return
     */
    private List<User> filterUserInfo(String inputInfo) {

        List<User> filter = new ArrayList<>();
        for (User userInfo : userInfos) {
            //如果集合中的phone包含输入的信息,则添加到过滤集合中
            if (userInfo.phone.contains(inputInfo)) {
                filter.add(userInfo);
            }
        }
        return filter;
    }


    /**
     * 设置登录的类型
     *
     * @param phoneViisible  手机登录的控件显示
     * @param accountVisible 账号登录的控件显示
     * @param login_account  账号描述的R.string的文字描述
     * @param login_password 密码描述的R.string的文字描述
     * @param isFocusable    是否获取焦点
     * @param passwordHint
     */
    public void setLoginType(int phoneViisible, int accountVisible, int recordVisible, int login_account, int login_password, boolean isFocusable, int passwordHint) {

        //设置获取验证码按钮的显示
        mBtnGetSecurityCode.setVisibility(phoneViisible);
        //设置显示密码按钮的显示
        mCbShowPassword.setVisibility(accountVisible);
        //设置显示pupupwindow按钮的显示
        mIvShowRecord.setVisibility(recordVisible);

        //设置焦点
        mBtnGetSecurityCode.setFocusable(isFocusable);
        mCbShowPassword.setFocusable(!isFocusable);
        mIvShowRecord.setFocusable(!isFocusable);

        //设置描述图片
        mIvAccount.setImageResource(login_account);
        mIvPassword.setImageResource(login_password);

        //设置类型选择的焦点
        mRbAccount.setFocusable(isFocusable);
        mRbPhone.setFocusable(!isFocusable);

        //设置密码的Hint文本
        mPassword.setHint(passwordHint);

        mAccount.setText("");
        mPassword.setText("");

        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }

        mCbShowPassword.setChecked(false);
    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }

    /**
     * 控件的点击事件
     */
    private class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {

            CommonUtils.hideSoftKeyboard(LoginActivity.this);

            switch (view.getId()) {

                case R.id.btn_login_get_security_code:
                    //获取验证码

                    final String phone = mAccount.getText();
                    //判断手机号是否正确
                    boolean isPhone = Tools.isMobilePhoneNumber(phone);
                    if (!isPhone) {
                        MyToast.show(LoginActivity.this, "请输入正确的手机号");
                        return;
                    }

                    //获取验证码
                    SecurityCodeUtils.getCode(LoginActivity.this , phone, 2 ,0 ,new VerfyCallback() {

                        @Override
                        public void onSuccess() {
                            timerUtils = new TimerUtils() ;
                            timerUtils.startTimer(LoginActivity.this , mBtnGetSecurityCode);
                            MyToast.show(LoginActivity.this,"验证码已发送至:"+phone);
                        }

                        @Override
                        public void onError(BaseEntity.MyError mError) {
                            DialogFactory.warningDialog(LoginActivity.this,mError.msg);
                        }

                        @Override
                        public void onLoadIndicatorDataCallback(List<IndicatorInfos> indicatorInfos) {

                        }
                    });

                    break;

                case R.id.btn_login_in:
                    //登录
                    String userName = mAccount.getText();
                    String password = mPassword.getText();
                    //检查输入的用户名密码是否符合规范
                    boolean result = checkInput(userName, password);
                    if (result) {
                        User user = new User();
                        user.phone = userName;
                        user.password = password;

                        //将用户添加到集合中
                        addToList(user);

                        if (type == ACCOUNT_TYPE) {
                            //账号登录
                            accountLogin(user.phone,user.password) ;
                        } else if (type == PHONE_TYPE) {
                            //验证码登录
                            phoneLogin(user.phone,user.password) ;
                        }

                    }
                    break;

                case R.id.btn_login_look:
                    //随便看看
                    setResult(RESULT_OK);
                    finish();
                    break;

                case R.id.btn_login_regist:
                    //注册
                    UIUtils.startActivity(LoginActivity.this, RegistActivity.class);
                    break;

                case R.id.iv_login_show_record:

                    //显示历史记录,弹出popupWindow
                    showPupWindow();

                    break;
                case R.id.btn_find_pwd:

                    //点击忘记密码
                    UIUtils.startActivity(LoginActivity.this , ChangePwdByPhoneActivity.class);
                    break;

//                case R.id.sv_login :
//
//                    //隐藏键盘
//                    CommonUtils.hideSoftKeyboard(LoginActivity.this);
//                    break;
            }
        }
    }

    /**
     * 手机验证码登录
     * @param phone
     * @param password
     */
    private void phoneLogin(String phone,String password) {

        Map<String, Object> infos = new HashMap<>();

        infos.put("phone", phone);
        infos.put("verifycodes" , password) ;

        loadingDialog = DialogFactory.getLoadingDialog(LoginActivity.this);
        DialogFactory.showDialog(loadingDialog);
        MyHttp.requestByFailCallback(Constants.BASE_URL + Constants.POST_SECURIT_CODE_LOGIN_URL, infos, MyHttp.POST, LoginActivity.this, false, null, new SimplePaserJsonCallback() {

            @Override
            public void onVerifyIsNull() {
            }
            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
                try {
                    parseJson(dataRaw);
                } catch (Exception e) {
                    MyLog.e(TAG, "解析json错误");
                    e.printStackTrace();
                }
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }

            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                super.onErrorCodeError(mError);
                DialogFactory.dismissLoadingDialog(loadingDialog);
                if (errorDialog == null) {
                    errorDialog = DialogFactory.warningDialog(LoginActivity.this, mError.msg);
                }else if (!errorDialog.isShowing()){
                    errorDialog = DialogFactory.warningDialog(LoginActivity.this, mError.msg);
                }
            }
        }, new HttpFailCallback(){

            @Override
            public void onServiceErrorCallback() {
            }
        });
    }

    /**
     * 账号登录
     * @param  phone
     * @param  password
     */
    private void accountLogin(String phone,String password) {
        loadingDialog = DialogFactory.getLoadingDialog(LoginActivity.this);
        DialogFactory.showDialog(loadingDialog);
        Map<String,Object> maps = new HashMap<>();
        maps.put("phone",phone);
        maps.put("password", Des3.getEncodePWD(password));
        MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_LOGIN_URL, maps, MyHttp.POST, LoginActivity.this, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {

            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
                DialogFactory.dismissLoadingDialog(loadingDialog);
                try {
                    parseJson(dataRaw);
                } catch (Exception e) {
                    MyLog.e(TAG, "解析json错误");
                    e.printStackTrace();
                }
            }
            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                super.onErrorCodeError(mError);
                DialogFactory.dismissLoadingDialog(loadingDialog);
                DialogFactory.warningDialog(LoginActivity.this, mError.msg);
            }
        });
    }


    /**
     * 展示popupWindow
     */
    private void showPupWindow() {
        if (popupWindow == null) {
            //弹出PopupWindow
            initListView();
        }

        isArrowDown.set(true);

        //当popupWindow关闭时显示
        if (popIsShowing.get()) {
            popIsShowing.set(false);
        } else {
            if (userInfos != null && userInfos.size() > 0) {
                try {
                    popupWindow.showAsDropDown(mIvAccount, 0, 0);
                    popIsShowing.set(true);
                } catch (Exception e) {
                    MyLog.e(TAG, "pop显示异常：" + e.toString());
                }
            }
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isArrowDown.set(false);
            }
        }, 2000);
    }

    /**
     * 将点击输入的用户信息存入集合
     *
     * @param user
     */
    private void addToList(User user) {
        if (userInfos != null) {
            for (User userInfo : userInfos) {
                if (userInfo.phone.equals(user.phone)) {
                    return;
                }
            }
            userInfos.add(user);
        }
    }

    /**
     * 解析返回的Json数据
     *
     * @param dataRaw 回调的Json
     */
    private void parseJson(String dataRaw) {
        Gson gson = new Gson();
        User user = gson.fromJson(dataRaw, User.class);
        // 1.存入数据库
        if (user != null) {
           //记录已登录
            MyApp.loginUserUid = user.userid;
            CacheUtils.cacheBooleanData(LoginActivity.this, Constants.IS_LOGIN_KEY, true);
            CacheUtils.cacheIntData(LoginActivity.this, Constants.LOGIN_UID, user.userid);
            CacheUtils.cacheStringData(LoginActivity.this, Constants.LOGIN_USER_NAME, user.consumersname);
            //存入数据库
            if (UserDaoImpl.getIntance(LoginActivity.this).isExists(user.userid)) {
                User oldUser = UserDaoImpl.getIntance(LoginActivity.this).findByQuery(user.userid);
                user.setId(oldUser.getId());
                UserDaoImpl.getIntance(LoginActivity.this).updata(user);
            } else {
                UserDaoImpl.getIntance(LoginActivity.this).insert(user);
            }
            setAlias(MyApp.imei+"_"+user.userid);
            CommonUtils.reportImei(LoginActivity.this);
//            setResult(RESULT_OK);
            MainHomeDataObserver.getInstance().hasNewMes(true);
            finish();
        }
        // 2.回到主页
        // 3.重新拉取主页数据
        // 4.
    }

    /**
     * 验证输入
     *
     * @param userName
     * @param password
     * @return
     */
    private boolean checkInput(String userName, String password) {

        if (Tools.isEmpty(userName)) {
            MyToast.show(LoginActivity.this, "手机号不能为空");
            return false;
        }

        //判断输入是否是手机号
        boolean isPhone = Tools.isMobilePhoneNumber(userName);

        if (!isPhone) {
            MyToast.show(LoginActivity.this, "请输入正确的手机号");
            return false;
        }

        if (Tools.isEmpty(password)) {
            if (type == ACCOUNT_TYPE) {
                MyToast.show(LoginActivity.this, "密码不能为空");
            } else if (type == PHONE_TYPE) {
                MyToast.show(LoginActivity.this, "请输入验证码!");
            }
            return false;
        }
        return true;

    }

    /**
     * 初始化pupupwindow和其中的ListView
     */
    private ListView initListView() {

        //创建ListView
        ListView listView = new ListView(this);

        //设置背景
//        listView.setBackground(getResources().getDrawable(R.drawable.me_item_pressed_selector));

        //设置垂直滚轮不显示
        listView.setVerticalScrollBarEnabled(false);

        //设置ListView的adapter
        adapter = new MyAdapter(userInfos);
        listView.setAdapter(adapter);

        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        // 创建PopupWindow
        popupWindow = new PopupWindow(getApplicationContext());

        // 设置宽度(帐户容器的宽度)
        popupWindow.setWidth(mAccountLayout.getWidth());
        popupWindow.setHeight(layoutParams.height);

        // 设置布局
        popupWindow.setContentView(listView);

        // 设置超出pop范围点击关闭PoppuWindow
        popupWindow.setOutsideTouchable(true);

        //设置焦点(为了防止点击展开控件的时候重复弹出popupWindow)
        popupWindow.setFocusable(true);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popIsShowing.set(false);
            }
        });

        // 设置popupWindow背景
        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.white)));

        // 监听Listview的条目点击事件
        listView.setOnItemClickListener(new MyOnItemClickListener());

        return listView;
    }

    /**
     * 弹出popupWindow中listView的Adapter
     */
    private class MyAdapter extends BaseAdapter {

        private List<User> infos;

        public MyAdapter(List<User> userInfos) {
            this.infos = userInfos;
        }

        public void setUserInfos(List<User> infos) {
            this.infos = infos;
        }

        @Override
        public int getCount() {
            return infos == null ? 0 : infos.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {

            ViewHolder holder = null;

            if (convertView == null) {
                convertView = View.inflate(LoginActivity.this, R.layout.item_login_show_popup, null);
                holder = new ViewHolder();
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_login_item_name);
                holder.ivClear = (ImageView) convertView.findViewById(R.id.iv_login_item_clear);
                holder.ivPhoto = (ImageView) convertView.findViewById(R.id.iv_login_item_photo);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final User user = infos.get(position);

            //设置手机号和头像
            holder.tvName.setText(user.phone);

            Bitmap bitmap = BitmapUtils.getBitmap(user.imageLocalPath, 200, 200);
            if (bitmap != null) {
                holder.ivPhoto.setImageBitmap(bitmap);
            } else {
                holder.ivPhoto.setImageResource(R.drawable.chat_default_user_header);
            }
            holder.ivClear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    //点击删除按钮时将当前用户信息从数据库删除
                    UserDaoImpl.getIntance(LoginActivity.this).delete(user.getId());
                    infos.remove(user);
                    notifyDataSetChanged();

                    //当集合没有数据时隐藏弹出框按钮
                    if (userInfos == null || userInfos.size() < 1) {
                        mIvShowRecord.setVisibility(View.GONE);
                        popupWindow.dismiss();
                    }
                }
            });

            return convertView;
        }
    }

    private class ViewHolder {
        private TextView tvName;
        private ImageView ivClear;
        private ImageView ivPhoto;
    }

    /**
     * listView的条目点击事件
     */
    private class MyOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            //设置用户信息
            User user = userInfos.get(i);
            mAccount.setText(user.phone);
            mPassword.setText(user.password);
            adapter.notifyDataSetChanged();
            popupWindow.dismiss();

            //设置光标到最后
            mAccount.setSelection(user.phone.length());
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        Intent intent = getIntent();
        fromtype = intent.getIntExtra("type",0);

        if(fromtype == JPUSH){
            String os_version = intent.getStringExtra("os_version");
            String os_platform = intent.getStringExtra("os_platform");
            MessageDialog dialog = DialogFactory.chooseDialog(LoginActivity.this, "您的帐号已经在["+os_platform+"]-["+os_version+"上登录，如果您需要继续使用,请重新登录。", "登录", "退出", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CacheUtils.cacheBooleanData(LoginActivity.this, Constants.IS_LOGIN_KEY, true);
                    setAlias(MyApp.imei+"_"+CacheUtils.getIntData(getApplicationContext(), Constants.LOGIN_UID, 0));
                    CommonUtils.reportImei(LoginActivity.this);
                    Intent intent3 = new Intent(LoginActivity.this, MainActivity.class);
                    intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    startActivity(intent3);
                    finish();
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //清除栈
                }
            });
            dialog.setTitle(R.string.app_tip);
            dialog.show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        //清除集合数据并从数据库查找用户信息
        if (userInfos != null && userInfos.size() > 0) {
            userInfos.clear();
        }
        userInfos = UserDaoImpl.getIntance(LoginActivity.this).findAll();

        if (timerUtils != null && timerUtils.timerIsRunning()){
            timerUtils.stopTimer(mBtnGetSecurityCode);
        }

        //弹出框按钮的显示
        if (userInfos == null) {
            mIvShowRecord.setVisibility(View.GONE);
            return;
        }

        if(type == ACCOUNT_TYPE){

            if (userInfos.size() < 1) {
                mIvShowRecord.setVisibility(View.GONE);
            } else {
                mIvShowRecord.setVisibility(View.VISIBLE);
            }
        }else{
            mIvShowRecord.setVisibility(View.GONE);
        }
    }

    private final Handler mJpushHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    //测试注销推送
                    break;

                case MSG_SET_TAGS:
                    Log.d(TAG, "Set tags in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };


    /**
     * 别名回调接口
     */

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mJpushHandler.sendMessageDelayed(mJpushHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }

//            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };
    /**
     * 标签回调接口
     */
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mJpushHandler.sendMessageDelayed(mJpushHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }

            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };

    /**
     * 设置tag(区域码)
     * @param tag
     */
    private void setJpushTag(String tag){

        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {
//			Toast.makeText(PushSetActivity.this,R.string.error_tag_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        // ","隔开的多个 转换成 Set
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!ExampleUtil.isValidTagAndAlias(sTagItme)) {
//				Toast.makeText(PushSetActivity.this,R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show();
                return;
            }
            tagSet.add(sTagItme);
        }

        //调用JPush API设置Tag
        mJpushHandler.sendMessage(mJpushHandler.obtainMessage(MSG_SET_TAGS, tagSet));

    }
    /**
     * 设置别名(imei)
     * @param alias
     */
    private void setAlias(String alias){
        MyLog.d(TAG,"set alias : "+alias);
//		EditText aliasEdit = (EditText) findViewById(R.id.et_alias);
//		String alias = aliasEdit.getText().toString().trim();
        if (TextUtils.isEmpty(alias)) {
//			Toast.makeText(PushSetActivity.this,R.string.error_alias_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!ExampleUtil.isValidTagAndAlias(alias)) {
//			MyToast.show(LoginActivity.this,"推送别名不符合规则 :"+alias);
            return;
        }
//        MyToast.show(LoginActivity.this,"推送别名是 :"+alias);
        //调用JPush API设置Alias
        mJpushHandler.sendMessage(mJpushHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }
}
